from langchain_openai import OpenAI
from langchain.prompts import PromptTemplate
from langchain_core.runnables import RunnableSequence
import jieba
import jieba.analyse
from typing import List, Dict
import logging

class SentimentAnalyzer:
    def __init__(self, api_key: str):
        self.llm = OpenAI(
            openai_api_key=api_key,
            temperature=0.7
        )
        self.logger = logging.getLogger(__name__)
        
        # 定义情感分析提示模板
        self.prompt = PromptTemplate(
            input_variables=["text"],
            template="分析以下文本的情感倾向：{text}\n情感倾向是："
        )
        
        # 使用新的 RunnableSequence 替代 LLMChain
        self.chain = self.prompt | self.llm

    def analyze(self, text: str) -> str:
        """
        分析文本情感
        """
        try:
            # 使用新的调用方式
            result = self.chain.invoke({"text": text})
            return result.strip()
        except Exception as e:
            self.logger.error(f"Error analyzing sentiment: {str(e)}")
            return "分析失败"

    def extract_keywords(self, text: str, top_k: int = 10) -> List[str]:
        """
        提取关键词
        """
        try:
            keywords = jieba.analyse.extract_tags(text, topK=top_k)
            return keywords
        except Exception as e:
            self.logger.error(f"Error extracting keywords: {str(e)}")
            return []

    def analyze_batch(self, texts: List[str]) -> List[Dict]:
        """
        批量分析文本
        """
        results = []
        for text in texts:
            sentiment = self.analyze(text)
            keywords = self.extract_keywords(text)
            results.append({
                'text': text,
                'sentiment': sentiment,
                'keywords': keywords
            })
        return results

    def get_sentiment_statistics(self, results: List[Dict]) -> Dict:
        """
        获取情感统计信息
        """
        stats = {
            'positive': 0,
            'negative': 0,
            'neutral': 0
        }
        
        for result in results:
            sentiment = result['sentiment']
            if sentiment == '正面':
                stats['positive'] += 1
            elif sentiment == '负面':
                stats['negative'] += 1
            else:
                stats['neutral'] += 1
                
        return stats 